package org.jeecg.modules.goodsorder.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.models.auth.In;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.dto.message.BusMessageDTO;
import org.jeecg.common.api.dto.message.MessageDTO;
import org.jeecg.common.api.dto.message.TemplateMessageDTO;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.goods.entity.Goods;
import org.jeecg.modules.goods.mapper.GoodsMapper;
import org.jeecg.modules.goodsorder.entity.GoodsOrder;
import org.jeecg.modules.goodsorder.entity.GoodsOrderDetail;
import org.jeecg.modules.goodsorder.mapper.GoodsOrderDetailMapper;
import org.jeecg.modules.goodsorder.mapper.GoodsOrderMapper;
import org.jeecg.modules.goodsorder.service.IGoodsOrderService;
import org.jeecg.modules.order.entity.Order;
import org.jeecg.modules.order.mapper.OrderMapper;
import org.jeecg.modules.recharge.entity.Balance;
import org.jeecg.modules.recharge.mapper.BalanceMapper;
import org.jeecg.modules.system.entity.SysAnnouncement;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.voucher.entity.Voucher;
import org.jeecg.modules.voucher.mapper.VoucherMapper;
import org.jeecg.modules.voucher.service.IVoucherService;
import org.jeecg.modules.zixishi.entity.Quyu;
import org.jeecg.modules.zixishi.entity.Seat;
import org.jeecg.modules.zixishi.service.IQuyuService;
import org.jeecg.modules.zixishi.service.ISeatService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 商品订单
 * @Author: jeecg-boot
 * @Date:   2024-07-11
 * @Version: V1.0
 */
@Service
public class GoodsOrderServiceImpl extends ServiceImpl<GoodsOrderMapper, GoodsOrder> implements IGoodsOrderService {

	@Autowired
	private GoodsMapper goodsMapper;
	@Autowired
	private GoodsOrderMapper goodsOrderMapper;
	@Autowired
	private GoodsOrderDetailMapper goodsOrderDetailMapper;
	@Autowired
	private BalanceMapper balanceMapper;
	@Autowired
	private OrderMapper orderMapper;
	@Autowired
	private ISysBaseAPI sysBaseApi;
	@Autowired
	private ISysUserService sysUserService;
	@Autowired
	private IQuyuService quyuService;
	@Autowired
	private ISeatService seatService;
	@Autowired
	private ISysDictService sysDictService;
	@Autowired
	private WxMpService wxMpService;
	@Autowired
	private VoucherMapper voucherMapper;
    @Autowired
    private RedisUtil redisUtil;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveMain(GoodsOrder goodsOrder, List<GoodsOrderDetail> goodsOrderDetailList) {
		goodsOrderMapper.insert(goodsOrder);
		if(goodsOrderDetailList!=null && goodsOrderDetailList.size()>0) {
			for(GoodsOrderDetail entity:goodsOrderDetailList) {
				//外键设置
				entity.setOrderId(goodsOrder.getId());
				goodsOrderDetailMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateMain(GoodsOrder goodsOrder,List<GoodsOrderDetail> goodsOrderDetailList) {
		goodsOrderMapper.updateById(goodsOrder);
		
		//1.先删除子表数据
		goodsOrderDetailMapper.deleteByMainId(goodsOrder.getId());
		
		//2.子表数据重新插入
		if(goodsOrderDetailList!=null && goodsOrderDetailList.size()>0) {
			for(GoodsOrderDetail entity:goodsOrderDetailList) {
				//外键设置
				entity.setOrderId(goodsOrder.getId());
				goodsOrderDetailMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delMain(String id) {
		goodsOrderDetailMapper.deleteByMainId(id);
		goodsOrderMapper.deleteById(id);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			goodsOrderDetailMapper.deleteByMainId(id.toString());
			goodsOrderMapper.deleteById(id);
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void doOrder(LoginUser sysUser, GoodsOrder order, List<GoodsOrderDetail> detailList) {
		order.setOrderStatus("0");
		order.setOrderNum("" + FillRuleUtil.executeRule("shop_order_num", new JSONObject()));
		order.setSysUserId(sysUser.getId());
		order.setOrderName("商品购买订单");

		LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<Order>();
		queryWrapper.eq(Order::getSysUserId, sysUser.getId())
				.in(Order::getOrderStatus, "1","2")
				.orderByDesc(Order::getOrderStatus)
				.orderByAsc(Order::getStartTime)
				.last("limit 1");

		Order seatOrder = orderMapper.selectOne(queryWrapper);
		if(null!=seatOrder) {
			order.setSeatOrderNum(seatOrder.getOrderNum());
		}
		goodsOrderMapper.insert(order);
		for(GoodsOrderDetail entity:detailList) {
			String goodsId = entity.getGoodsId();
			Integer cnt = entity.getCnt();
			Goods goods = goodsMapper.selectById(goodsId);
			goods.setId(null);
			GoodsOrderDetail detail = new GoodsOrderDetail();
			BeanUtils.copyProperties(goods, detail);
			detail.setGoodsId(goodsId);
			detail.setOrderId(order.getId());
			detail.setCnt(cnt);
			goodsOrderDetailMapper.insert(detail);
		}
		if(StringUtils.isNotBlank(order.getVoucherId())) {
			Voucher	voucher = voucherMapper.selectById(order.getVoucherId());
			voucher.setUseStatus(1);
			voucherMapper.updateById(voucher);
		}
		redisUtil.set("goodsorder:quxiao:" + order.getOrderNum(), "", 5*60);
	}

	@Override
	@Transactional
	public void payOrder(LoginUser sysUser, GoodsOrder order, Balance balance) {
		balance.setBalance(new BigDecimal(balance.getBalance().floatValue() - Float.valueOf(order.getOrderMoney())));
		balanceMapper.updateById(balance);
		order.setPayType("1");
		order.setPayTime(new Date());
		order.setOrderStatus("1");
		goodsOrderMapper.updateById(order);
		this.sendMsg4Goods(order.getId());
		redisUtil.del("goodsorder:quxiao:" + order.getOrderNum());
	}

	public void sendMsg4Goods(String orderId) {
		GoodsOrder goodsOrder = goodsOrderMapper.selectById(orderId);
		if(goodsOrder==null) {
			return;
		}
		List<GoodsOrderDetail> detailList = goodsOrderDetailMapper.selectByMainId(orderId);

		String div = "";
		Order order = null;
		String user = "";
		String phone = "";
		String seatName = "";
		try{
			if(StringUtils.isNotEmpty(goodsOrder.getSeatOrderNum())){
				order = orderMapper.selectOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderNum, goodsOrder.getSeatOrderNum()));
			}
			if(null != order){
				user = order.getUname();
				phone = order.getUphone();
				Quyu quyu = quyuService.getById(order.getQuyuId());
				Seat seat = seatService.getById(order.getSeatId());
				seatName = quyu.getName() + "-->"+seat.getName();
			}
			SysUser sysUser = sysUserService.getById(goodsOrder.getSysUserId());
			if(null!=sysUser){
				if(StringUtils.isBlank(user)){
					user = sysUser.getRealname();
				}
				if(StringUtils.isBlank(phone)){
					phone = sysUser.getPhone();
				}
			}
			div = "<div>座位号："+seatName+"</div><div>用&nbsp;&nbsp;户："+user+"</div><div>电&nbsp;&nbsp;话："+phone+"</div>";

		}catch (Exception ex){
			log.error(ex.getMessage());
		}

		String status = "未支付";
		if(StringUtils.equals("1",goodsOrder.getOrderStatus())){
			status = "已支付";
		}
		String str = "<h1>&nbsp; &nbsp;"+goodsOrder.getOrderNum()+"("+status+")</h1>";
		if(CollectionUtil.isNotEmpty(detailList)){
			str += "<ul>";
			for(GoodsOrderDetail detail:detailList) {
				str += "<li>&nbsp; &nbsp;"+detail.getCnt()+"&nbsp; x &nbsp; "+detail.getName()+"</li>";
			}
			str += "</ul>";
		}
		String remark = StringUtils.isNotBlank(goodsOrder.getRemark())?goodsOrder.getRemark():"无";
		str += "<div>备注："+remark+"</div>";
		str+=div;
		MessageDTO msg = new MessageDTO();
		msg.setFromUser("admin");
		List<DictModel> configs = sysDictService.getDictItems("msg_receiver");
		Set<String> adminVals = new HashSet<>();
		if (null != configs && configs.size() > 0) {

			for (DictModel dictModel : configs) {
				adminVals.add(dictModel.getValue());
			}
		}
		msg.setToUser(CollectionUtil.join(adminVals, ","));
		msg.setContent(str);
		msg.setTitle("商品已付款通知");
		msg.setPriority(CommonConstant.PRIORITY_H);
		sysBaseApi.sendSysAnnouncement(msg);

		try {
			List<DictModel> configs1 = sysDictService.getDictItems("goodorder_receiver");
			Set<String> adminVals1 = new HashSet<>();
			if (null != configs1 && configs1.size() > 0) {

				for (DictModel dictModel : configs1) {
					adminVals1.add(dictModel.getValue());
				}
			}
			//公众号模板消息
			//5qNrTu0mk1bbLOxz05dmbWzQ37UrPHlNM0BW3T7oalE
			List<WxMpTemplateData> data = new ArrayList<>();
			data.add(new WxMpTemplateData("character_string1", goodsOrder.getOrderNum()));//订单编号
			data.add(new WxMpTemplateData("thing2", "商品订单已支付")); //服务类型
			data.add(new WxMpTemplateData("time6", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(goodsOrder.getPayTime()))); //下单时间
			data.add(new WxMpTemplateData("thing16", user + "("+phone+")")); //用户名
			if(CollectionUtil.isNotEmpty(adminVals1)){
				for (String adminVal : adminVals1) {
					wxMpService.getTemplateMsgService().sendTemplateMsg(WxMpTemplateMessage.builder()
						.toUser(adminVal)
						.templateId("5qNrTu0mk1bbLOxz05dmbWzQ37UrPHlNM0BW3T7oalE")
						.url("")
						.data(data)
						.build());
				}
			}
		}catch (Exception e){
			log.error(e.getMessage());
		}
	}

	@Override
	public IPage<GoodsOrder> pageList(Page<GoodsOrder> page, Wrapper<GoodsOrder> queryWrapper) {
		return goodsOrderMapper.pageList(page, queryWrapper);
	}
}
